#include "Master.h"

Master::Master()
{

}

void Master::SetParameters(char* _buffer, int _bufferSize){
	this->buffer = _buffer;
	this->bufferSize = _bufferSize;
}

void Master::SendSetBufferSize(int slaveId, int slaveBufferSize){
	int newSize = slaveBufferSize;
	memcpy(buffer, &newSize, 4);
	printf("#Master: SEND TAG_SET_BUFFER_SIZE to %d\n", slaveId);
	
	MPI_Isend (buffer, bufferSize, MPI_CHAR,
					   slaveId, TAG_SET_BUFFER_SIZE, MPI_COMM_WORLD, &request);
	MPI_Wait (&request, &status);
}

void Master::SendResetBufferSize(int slaveId){
	printf("#Master: SEND TAG_RESET_BUFFER_SIZE to %d\n", slaveId);
	
	MPI_Isend (buffer, bufferSize, MPI_CHAR,
					   slaveId, TAG_RESET_BUFFER_SIZE, MPI_COMM_WORLD, &request);
	MPI_Wait (&request, &status);
}

void Master::SendCloseAllThreads(int slaveId){
	printf("#Master: SEND TAG_CLOSE_ALL_THREADS to %d\n", slaveId);
	
	MPI_Isend (buffer, bufferSize, MPI_CHAR,
					   slaveId, TAG_CLOSE_ALL_THREADS, MPI_COMM_WORLD, &request);
	MPI_Wait (&request, &status);
}

void Master::SendSync(int slaveId){
	printf("#Master: SEND TAG_SYNC to %d\n", slaveId);
	
	MPI_Isend (buffer, bufferSize, MPI_CHAR,
					   slaveId, TAG_SYNC, MPI_COMM_WORLD, &request);
	MPI_Wait (&request, &status);
}

void Master::SendTerminateSlave(int slaveId){
	printf("#Master: SEND TAG_TERMINATE_SLAVE to %d\n", slaveId);
	
	MPI_Isend (buffer, bufferSize, MPI_CHAR,
					   slaveId, TAG_TERMINATE_SLAVE, MPI_COMM_WORLD, &request);
	MPI_Wait (&request, &status);
}

void Master::SendJob(int slaveId, char* jobBuffer, int jobBufferSize){
	printf("#Master: SEND TAG_JOB to %d\n", slaveId);
	
	MPI_Isend (jobBuffer, jobBufferSize, MPI_CHAR,
					   slaveId, TAG_JOB, MPI_COMM_WORLD, &request);
	MPI_Wait (&request, &status);
}

int Master::SlaveHasAnyMessage(int slaveId){
	int flag = 0;
	MPI_Iprobe(slaveId, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status);
	
	if (flag==0){
		return 0;
	}
	
	if (flag<0){
		return 0;
	}
	
	if (flag>0){
		return 1;
	}
}

void Master::Receive(int fromSlaveId, char* buffer, int bufferSize){
	printf("#Master: Receiving from %d\n", fromSlaveId);
	MPI_Irecv (buffer, bufferSize, MPI_CHAR, fromSlaveId, TAG_JOB, MPI_COMM_WORLD,
					   &request);
	MPI_Wait (&request, &status);
	printf("#Master: Received from %d\n", fromSlaveId);
}
